<?php

namespace app\api\controller;

use app\admin\model\ClassAddress;
use app\admin\model\Club;
use app\admin\model\ClubDtl;
use app\admin\model\SearchShool;
use app\admin\model\TeacherArea;
use app\admin\model\TeacherCollection as TeacherCollectionModel;
use app\admin\model\TeacherCollectionMain;
use app\admin\model\TeacherCourseDisplay;
use app\admin\model\TeacherDetail;
use app\common\controller\Api;
use think\Db;

/**
 * 收藏教师接口
 */
class TeacherCollection extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    //收藏教师课程列表
    public function collection_list(){
        $params = $this->request->param();
        if(!isset($params['page'])||!$params['page']){
            $params['page'] = 1;
        }
        if(!isset($params['page_size'])||!$params['page_size']){
            $params['page_size'] = 10;
        }

        // 验证用户登录
        $user = $this->auth->getUser();
        if(!isset($user['id'])||!$user['id']){
            $this->error('当前登录用户不存在');
        }

        // 查询主表：获取收藏的教师列表
        $query = TeacherCollectionMain::where(['user_id' => $user['id']])
            ->with(['identity'])
            ->order('id', 'desc')
            ->paginate($params['page_size']);

        $list = $query->getCollection();
        
        // 获取所有收藏的教师身份ID
        $info_ids = [];
        foreach ($list as $v) {
            if (isset($v['info_id']) && $v['info_id']) {
                $info_ids[] = $v['info_id'];
            }
        }
        
        // 查询子表：获取用户收藏的所有课程
        $collections = [];
        if (!empty($info_ids)) {
            $collectionList = TeacherCollectionModel::where(['user_id' => $user['id']])
                ->with(['teacherDetailS'])
                ->select();
            
            // 按 info_id 分组
            foreach ($collectionList as $col) {
                if (isset($col['teacher_detail_s']['info_id'])) {
                    $info_id = $col['teacher_detail_s']['info_id'];
                    if (!isset($collections[$info_id])) {
                        $collections[$info_id] = [];
                    }
                    $collections[$info_id][] = $col;
                }
            }
        }
        
        $arr = [];
        foreach ($list as $k => $v) {
            $info_id = isset($v['info_id']) ? $v['info_id'] : 0;
            $identity = isset($v['identity']) ? $v['identity'] : [];
            
            // 教师信息
            $arr[$k]['id'] = isset($identity['id']) ? $identity['id'] : '';
            $arr[$k]['user_id'] = isset($identity['user_id']) ? $identity['user_id'] : '';
            $arr[$k]['name'] = isset($identity['name']) ? $identity['name'] : '';
            $arr[$k]['avatar'] = isset($identity['user']['avatar']) ? $identity['user']['avatar'] : '';
            
            // 构建课程信息到 dtl 数组
            $teacher_detail = [];
            if (isset($collections[$info_id])) {
                foreach ($collections[$info_id] as $kk => $col) {
                    $td = isset($col['teacher_detail_s']) ? $col['teacher_detail_s'] : [];
                    if (empty($td)) continue;
                    
                    $teacher_detail[$kk]['id'] = isset($td['id']) ? $td['id'] : '';
                    $teacher_detail[$kk]['info_id'] = isset($td['info_id']) ? $td['info_id'] : '';
                    $teacher_detail[$kk]['hourly_rate'] = isset($td['hourly_rate']) ? $td['hourly_rate'] : '';
                    $teacher_detail[$kk]['club_name'] = isset($td['club_dtl_s']['name']) ? $td['club_dtl_s']['name'] : '';
                    $teacher_detail[$kk]['club_img_url'] = isset($td['club_dtl_s']['img_url']) ? $td['club_dtl_s']['img_url'] : '';
                    $teacher_detail[$kk]['is_premium'] = isset($td['is_premium']) ? $td['is_premium'] : '';
                    $teacher_detail[$kk]['people'] = isset($td['people']) ? $td['people'] : '';
                    if(isset($td['work_time']) && $td['work_time'] > 0){
                        $teacher_detail[$kk]['work_time'] = $td['work_time'].'年';
                    }else{
                        $teacher_detail[$kk]['work_time'] = '';
                    }
                    // 收藏列表中的课程都是已收藏的
                    $teacher_detail[$kk]['is_collected'] = 1; // 1已收藏
                }
            }
            
            $arr[$k]['dtl'] = array_values($teacher_detail);
            
            // 教师级别的其他信息
            $week = isset($identity['appointment_time_week']) ? $identity['appointment_time_week'] : '';
            $time = isset($identity['appointment_time']) ? $identity['appointment_time'] : '';
            $arr[$k]['appointment_time_week']    = $week.' '.$time;
            $arr[$k]['appointment_time']    = $time;
            $arr[$k]['appointment_week']    = $week;
            
            // 使用5分制格式化评分
            $score = isset($identity['main_score']) ? $identity['main_score'] : '';
            $arr[$k]['score'] = $this->formatScore($score);
            $arr[$k]['people'] = isset($identity['people']) ? $identity['people'] : '';
            $arr[$k]['hourly_rate'] = isset($identity['lowest_hourly_rate']) ? $identity['lowest_hourly_rate'] : '';
            
            $area = isset($identity['area']) ? explode(',',$identity['area']) : [];
            $area_arr = TeacherArea::get_arr();
            $area_name = '';
            foreach ($area as $kk=>$vv){
                $area_name .= isset($area_arr[$vv]) ? $area_arr[$vv].',' : '';
            }
            $arr[$k]['area_name'] = trim($area_name,',');
            $arr[$k]['tag_me']    = isset($identity['tag_me']) ? $identity['tag_me'] : '';
            
            // 检查教师和课程是否隐藏
            // main_status: 1显示，2隐藏
            // detail_status: 1显示，2隐藏
            // 只有当两个都是1（显示）时，才为1（显示），任何一个为2（隐藏）就为2（隐藏）
            $main_status = isset($identity['main_status']) ? (int)$identity['main_status'] : 1;
            
            // 检查该教师的所有收藏课程的状态
            $all_visible = true;
            if (!empty($teacher_detail)) {
                // 收集所有课程ID
                $td_ids = [];
                foreach ($teacher_detail as $td_item) {
                    if (isset($td_item['id']) && $td_item['id']) {
                        $td_ids[] = $td_item['id'];
                    }
                }
                
                // 批量查询课程状态
                if (!empty($td_ids)) {
                    $td_status_list = TeacherDetail::where('id', 'in', $td_ids)
                        ->column('detail_status', 'id');
                    
                    foreach ($td_ids as $td_id) {
                        $detail_status = isset($td_status_list[$td_id]) ? (int)$td_status_list[$td_id] : 1;
                        if ($detail_status != 1) {
                            $all_visible = false;
                            break;
                        }
                    }
                }
            }
            
            // 两个同时不隐藏（都为1）才为1，任何一个为2就为2
            if ($main_status == 1 && $all_visible) {
                $arr[$k]['status'] = 1; // 显示
            } else {
                $arr[$k]['status'] = 2; // 隐藏
            }
        }

        $data = [
            'list' => $arr,
            'count' => $query->total()
        ];

        $this->success('收藏列表', $data);
    }

    //收藏教师课程
    public function add_collection(){
        $params = $this->request->param();
        if(!isset($params['teacher_detail_id'])||!$params['teacher_detail_id']){
            $this->error('教师课程id必传');
        }

        // 验证用户登录
        $user = $this->auth->getUser();
        if(!isset($user['id'])||!$user['id']){
            $this->error('当前登录用户不存在');
        }

        // 验证课程是否存在
        $teacherDetail = TeacherDetail::where(['id' => $params['teacher_detail_id']])->find();
        if(!$teacherDetail){
            $this->error('教师课程不存在');
        }

        $info_id = isset($teacherDetail['info_id']) ? $teacherDetail['info_id'] : 0;
        if(!$info_id){
            $this->error('教师课程信息不完整');
        }

        // 检查是否已收藏（子表）
        $exist = TeacherCollectionModel::where([
            'user_id' => $user['id'],
            'teacher_detail_id' => $params['teacher_detail_id']
        ])->find();

        if($exist){
            $this->error('该课程已收藏');
        }

        // 开启事务
        Db::startTrans();
        try {
            // 检查主表是否有该教师的收藏记录
            $mainExist = TeacherCollectionMain::where([
                'user_id' => $user['id'],
                'info_id' => $info_id
            ])->find();

            // 如果主表没有记录，创建主表记录
            if(!$mainExist){
                $mainData = [
                    'user_id' => $user['id'],
                    'info_id' => $info_id,
                    'addtime' => date('Y-m-d H:i:s')
                ];
                TeacherCollectionMain::create($mainData);
            }

            // 添加子表收藏记录
            $data = [
                'user_id' => $user['id'],
                'teacher_detail_id' => $params['teacher_detail_id'],
                'addtime' => date('Y-m-d H:i:s')
            ];

            TeacherCollectionModel::create($data);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('收藏失败：' . $e->getMessage());
        }
        $this->success('收藏成功');
    }

    //删除收藏教师课程
    public function del_collection(){
        $params = $this->request->param();

        // 验证用户登录
        $user = $this->auth->getUser();
        if(!isset($user['id'])||!$user['id']){
            $this->error('当前登录用户不存在');
        }

        // 验证参数：必须传id（子表的id）
        if(!isset($params['id']) || !$params['id']){
            $this->error('请传入收藏记录id');
        }

        // 处理id参数：可能是字符串（逗号分隔）或数组
        $ids = [];
        if(is_array($params['id'])){
            $ids = $params['id'];
        }else{
            // 字符串格式，按逗号分隔
            $ids = explode(',', $params['id']);
        }

        // 过滤空值和转换为整数
        $ids = array_filter(array_map('intval', $ids));
        if(empty($ids)){
            $this->error('无效的收藏记录id');
        }

        // 查询收藏记录（只能删除自己的收藏）
        $collections = TeacherCollectionModel::where('user_id', $user['id'])
            ->where('teacher_detail_id', 'in', $ids)
            ->select();

        if(!$collections){
            $this->error('收藏记录不存在或无权删除');
        }

        // 开启事务
        Db::startTrans();
        try {
            // 收集需要检查的 info_id（在删除前收集）
            $info_ids_to_check = [];
            $deleteIds = [];
            
            foreach($collections as $collection){
                $deleteIds[] = $collection->id;
                
                // 获取该课程对应的 info_id
                $teacherDetail = TeacherDetail::where(['id' => $collection['teacher_detail_id']])->find();
                if($teacherDetail && isset($teacherDetail['info_id']) && $teacherDetail['info_id']){
                    $info_ids_to_check[] = $teacherDetail['info_id'];
                }
            }

            // 删除子表收藏记录
            TeacherCollectionModel::where('id', 'in', $deleteIds)->where(['user_id'=>$user['id']])->delete();
            
            // 检查每个 info_id 是否还有其他收藏的课程，如果没有则删除主表记录
            $info_ids_to_check = array_unique($info_ids_to_check);
            foreach($info_ids_to_check as $info_id){
                // 查询该教师是否还有其他收藏的课程（通过子表关联查询）
                $remaining = Db::name('teacher_collection')
                    ->alias('tc')
                    ->join('teacher_detail td', 'tc.teacher_detail_id = td.id', 'LEFT')
                    ->where('tc.user_id', $user['id'])
                    ->where('td.info_id', $info_id)
                    ->count();
                
                // 如果没有其他收藏课程了，删除主表记录
                if($remaining == 0){
                    TeacherCollectionMain::where([
                        'user_id' => $user['id'],
                        'info_id' => $info_id
                    ])->delete();
                }
            }
            
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('取消收藏失败：' . $e->getMessage());
        }
        $this->success('取消收藏成功');
    }

    protected function formatScore($score)
    {
        if ($score === null || $score === '') {
            return $score;
        }
        if (is_numeric($score)) {
            $score = (float)$score;
            
            // 最简单最傻瓜式的判断
            // 小于等于0 -> 0
            if ($score <= 0) {
                return '0.0';
            }
            
            // 大于等于10 -> 5
            if ($score >= 10) {
                return '5.0';
            }
            
            // 其他情况：向下取整得到整数部分
            $intPart = (int)floor($score);
            
            // 判断是否为整数（分数的小数部分是否接近0）
            $isInteger = abs($score - $intPart) < 0.001;

            $formattedScore = $intPart * 0.5;
//            if ($isInteger) {
//                // 整数：n * 0.5
//                // 1 -> 0.5, 2 -> 1.0, 3 -> 1.5, 4 -> 2.0, ...
//                $formattedScore = $intPart * 0.5;
//            } else {
//                // 小数：(n+1) * 0.5
//                // 0.1-0.9 -> 0.5, 1.1-1.9 -> 1.0, 2.1-2.9 -> 1.5, ...
//                $formattedScore = ($intPart + 1) * 0.5;
//            }
            
            return number_format($formattedScore, 1, '.', '');
        }
        return $score;
    }
}
